package com.android.topview.watermelon.account.activity

import android.os.Bundle
import android.view.KeyEvent
import androidx.lifecycle.ViewModelProvider
import com.android.topview.watermelon.R
import com.android.topview.watermelon.account.viewmodel.AccountViewModel
import com.android.topview.watermelon.account.entity.Account
import com.android.topview.watermelon.base.BaseActivity
import com.android.topview.watermelon.util.getNow
import com.android.topview.watermelon.util.setTalkBackFocus
import com.android.topview.watermelon.util.showToast
import kotlinx.android.synthetic.main.activity_add_account.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class AddAccountActivity : BaseActivity() {

    private lateinit var mVmAccount: AccountViewModel

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(RESULT_CANCELED)
            finish()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_account)
        initData()
        initListener()
        tv_add_account_title.setTalkBackFocus()
    }

    private fun initListener() {
        iv_add_account_back.setOnClickListener {
            setResult(RESULT_CANCELED)
            finish()
        }
        btn_add_sure.setOnClickListener {

            if (et_description.text.isBlank()) {
                showToast("请不要留空描述")
                return@setOnClickListener
            }
            if (et_add_account_money_number.text.isBlank()) {
                showToast("请输入金额")
                return@setOnClickListener
            } else {
                launch(Dispatchers.IO) {
                    getAccountMes().let {
                        mVmAccount.addAccount(it)
                        intent.putExtra("isCost", it.isCost)
                        setResult(RESULT_OK, intent)
                        finish()
                    }
                }
            }
        }
    }


    private fun initData() {
        mVmAccount = ViewModelProvider(this).get(AccountViewModel::class.java)
    }

    private fun getAccountMes(): Account {
        val account = Account(0, false, "", getNow())
        account.money = et_add_account_money_number.text.toString().toLong()
        account.description = et_description.text.toString()
        var costFlag = false
        if (radio_cost.isChecked) {
            costFlag = true
        }
        if (radio_income.isChecked) {
            costFlag = false
        }
        account.isCost = costFlag

        return account
    }

}